﻿using System;
using System.IO;
using UnityEngine;

namespace Core
{
    public class NativeFileData : Component, IAwake, IFileData
    {
        private string root;
        private PrefixDict prefixDict;

        public void Awake()
        {
            root = $"{Application.persistentDataPath}/USER_DATA_PATH/";
            prefixDict = new PrefixDict(root);
        }

        public override void Dispose()
        {
            if (IsDisposed) return;
            base.Dispose();
        }

        public string Read(string path)
        {
            path = prefixDict[path];

            Utils.File.CreateFile(path);

            try
            {
                return File.ReadAllText(path);
            }
            catch
            {
                return string.Empty;
            }
        }

        public void Append(string path, string content)
        {
            path = prefixDict[path];

            Utils.File.CreateFile(path);

            using var sw = File.AppendText(path);
            sw.WriteLine(content);
        }

        public void Write(string path, string content)
        {
            path = prefixDict[path];

            Utils.File.CreateFile(path);

            File.WriteAllText(path, content);
        }

        public void Delete(string path)
        {
            path = prefixDict[path];

            if (File.Exists(path))
            {
                File.Delete(path);
            }
        }
    }
}
